# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Project Name: luffcity study project
File Name: select_func.py
Author: kij
Create Date: 2021/2/21
-------------------------------------------------
"""
import os
import pickle

from conf.config import BASE_DIR


# 选择方法
def select_func(next_list, last_func=None, class_name=None):
	for item in next_list:
		print(item, next_list[item][0])
	num = input("请输入选择:").strip()
	# 不是数字就退出继续选择
	if not num.isdecimal() or not num in next_list:
		select_func(next_list, next_list)
	# 如果是0就调用上个方法
	if int(num) == 0:
		last_func()

	next_list[num][1](class_name, last_func)


# 查询虽有用户列表然后找到登陆用户
def get_user(user_name, user_password):
	# print("传入用户名%s用户密码%s" %(user_name, user_password))
	file_path = os.path.join(BASE_DIR, "files", "user.pkl")
	if not os.path.exists(file_path):
		return None
	else:
		with open(file_path, mode='rb') as user_file:
			while True:
				try:
					user = pickle.load(user_file)
					# print("传入用户名%s用户密码%s" % (user.user_name, user.user_password))
					if user_name == user.user_name and user_password == user.user_password:
						return user
				except EOFError:
					break


# 创建对象并保存
def create_obj(obj, file_name):
	file_path = os.path.join(BASE_DIR, "files", file_name)
	with open(file_path, mode='ab') as user_file:
		# 存储对象
		pickle.dump(obj, user_file, protocol=2)


# 查询所有机构列表
def get_org_list(admin_name, file_name):
	obj_list = []
	file_path = os.path.join(BASE_DIR, "files", file_name)
	if not os.path.exists(file_path):
		return None
	else:
		with open(file_path, mode='rb') as user_file:
			while True:
				try:
					org = pickle.load(user_file)
					if admin_name == None:
						obj_list.append(org)
					elif admin_name == org.admin_name:
						obj_list.append(org)
				except EOFError:
					break
		return obj_list


# 查询机构课程列表
def get_school_class_list(org_name, file_name):
	obj_list = []
	file_path = os.path.join(BASE_DIR, "files", file_name)
	if not os.path.exists(file_path):
		return None
	else:
		with open(file_path, mode='rb') as user_file:
			while True:
				try:
					org = pickle.load(user_file)
					if org_name == org.org_name:
						obj_list.append(org)
				except EOFError:
					break
		return obj_list
